<template>
    <div>
        <el-page-header :icon="ArrowLeft">
  
            <template #title>
                <span @click="back">返回</span>
            </template>
  
            <template #content>
                <span class="fs-14"> 诊所管理 </span>
                <el-icon style="vertical-align: -3px;">
                    <Right />
                </el-icon>
                <span class="fs-14 cr-blue"> 医生信息 </span>
            </template>
        </el-page-header>
  
  
        <!-- 新增表单 -->
        <el-form ref="ruleFormRef" :model="form" label-width="120px" class="mt-12" :rules="rules">
            <el-form-item label="医生姓名" prop="dname">
                <el-input v-model="form.dname" class="input-width" placeholder="请输入医生姓名" size="large"/>
            </el-form-item>
            <el-form-item label="医生职称" prop="jontitle">
                <el-input v-model="form.jontitle" class="input-width"  placeholder="请输入医生职称" size="large"/>
            </el-form-item>
            <el-form-item label="任职诊所" prop="caddress">
                <el-input v-model="form.caddress" class="input-width" placeholder="请输入诊任职诊所" size="large"/>
            </el-form-item>
            <el-form-item label="医生擅长" prop="excel">
                <el-input v-model="form.excel" type="textarea" size="large" placeholder="请准确填写诊所特色信息，包括服务项目，有助于患者更好的了解诊所，并进行就诊治疗，请准确填写诊所特色信息，包括服务项目，有助于患者更好的了解诊所，并进行就诊治疗"/>
                <p class="flth">还可输入 <span class="flth-n">{{ descRemain }}</span> 字</p>
            </el-form-item>
  
  
            <!-- 上传图片 -->
            <el-form-item label="添加照片">
                <el-upload class="avatar-uploader" action="http://127.0.0.1:4523/m1/2587975-0-default/upload"
                    :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" size="large">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
                
            </el-form-item>
            <p class="flth" style="margin-left: 120px ;margin-bottom: 25px;">还可上传 <span class="flth-n">{{ imgsRemain }}</span> 张</p>
  
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    提交
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
  
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue'
  import { ArrowLeft, Right, Plus } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import type { UploadProps, FormInstance, FormRules } from 'element-plus'
  import { useNavigate } from '../hooks'
  import { useRoute } from 'vue-router'
  import { doctoradd, doctoredit, doctorlist } from '../api'
  
  // do not use same name with ref
  const form = reactive({
    dname: '',
    caddress: '',
    jontitle: '',
    excel: '',
    potato: []
  })
  
  
  const navigator = useNavigate()
  const navigateTo = (url: string) => {
    navigator.navigateTo(url)
  }
  const back = function () {
    console.log('back,....')
    navigator.back()
  }
  
  const route = useRoute()
  const id = ref(route.query.id)
  
  
  // 图片上传
  const imageUrl = ref('')
  
  const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
  ) => {
  
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    form.potato = response.data
  }
  
  
  const picWhiteList = ["image/jpeg", "image/png"]
  
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.type !== 'image/jpeg') {
    if (picWhiteList.indexOf(rawFile.type) === -1) {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
  }
  
  
  // 计算诊所特点还剩多少个字
  const descRemain = computed(() => {
    return 800 - form.excel.length
  })
  // 计算还能上传多少张图片
  const imgsRemain = computed(() => {
    return 1 - form.potato.length
  })
  
  
  // 验证规则
  const rules = reactive<FormRules>({
    dname: [
        { required: true, message: '请输入医生姓名', trigger: 'blur' },
        { min: 2, max: 5, message: '医生姓名在2到5位之间', trigger: 'blur' },
    ],
    caddress: [
        { required: true, message: '请输入任职诊所', trigger: 'blur' },
        { min: 3, max: 10, message: '任职诊所名称在3到10位之间', trigger: 'blur' },
    ],
    jontitle: [
        { required: true, message: '请输入医生职称', trigger: 'blur' },
    ],
    excel: [
        { required: true, message: '请输入医生擅长', trigger: 'blur' },
        { min: 1, max: 800, message: '医生擅长文本长度需要小于800字', trigger: 'blur' },
    ],
    potato: [
        { required: false, message: '请选择图片', trigger: 'blur' },
        { min: 0, max: 1, message: '最多上传五张图片', trigger: 'blur' },
    ]
  })
  
  const ruleFormRef = ref<FormInstance>()
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  onMounted(async()=>{
    resetForm()
  
    if(id.value){
      const res=await doctorlist({id:id.value})
      
  
      for(let key in res[0]){
        form[key]=res[0][key]
      }
  
      imageUrl.value=form.potato[0]
    }
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    console.log("提交表单", formEl)
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if(id.value){
              form.id=id.value
              const res=await doctoredit(form)
            }else{
              const res = await doctoradd(form)
            }
            // console.log('提交表单，把数据发送个接口!', form)
            
            navigateTo("/clinic/doctor")
  
  
        } else {
            console.log('error submit!', fields)
        }
    })
  }
  
  
  </script>
  
  <style scoped lang="scss">
  .input-width {
    width: 360px;
  }
  
  .avatar-uploader .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
  
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    text-align: center;
  }
  </style>